<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>10×10网格战棋游戏（带血量系统）</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    
    <style>
        /* 核心样式：确保网格为正方形 */
        .grid-container {
            width: 100%;
            max-width: 500px;
            margin: 0 auto;
        }
        
        .grid-wrapper {
            position: relative;
            width: 100%;
        }
        
        .grid-wrapper::after {
            content: "";
            display: block;
            padding-bottom: 100%; /* 关键：创建1:1的正方形比例 */
        }
        
        .grid-inner {
            position: absolute;
            top: 0;
            left: 0;
            bottom: 0;
            right: 0;
            display: grid;
            grid-template-columns: repeat(10, 1fr);
            grid-template-rows: repeat(10, 1fr);
        }
        
        /* 网格单元格样式 */
        .grid-cell {
            border: 1px solid #E5E7EB;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
            transition: all 0.2s;
            position: relative;
        }
        
        .grid-cell:hover {
            background-color: #f3f4f6;
            cursor: pointer;
        }
        
        /* 坐标标签样式 */
        .x-label, .y-label {
            background-color: #f3f4f6;
            font-weight: bold;
            color: #6b7280;
        }
        
        /* 军队单位样式 */
        .red-unit {
            background-color: #fee2e2;
            color: #dc2626;
            border: 1px solid #fecaca;
        }
        
        .blue-unit {
            background-color: #dbeafe;
            color: #2563eb;
            border: 1px solid #bfdbfe;
        }
        
        .unit-icon {
            width: 100%;
            height: 100%;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            font-size: 14px;
            position: relative;
            z-index: 10;
        }
        
        .health-bar {
            width: 80%;
            height: 4px;
            background-color: #e5e7eb;
            border-radius: 2px;
            margin-bottom: 2px;
            overflow: hidden;
        }
        
        .health-value {
            height: 100%;
            background-color: #10b981;
            transition: width 0.3s ease;
        }
        
        .health-low {
            background-color: #f59e0b;
        }
        
        .health-critical {
            background-color: #ef4444;
        }
        
        /* 攻击特效容器 */
        .effects-container {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            pointer-events: none;
            z-index: 50;
        }
        
        /* 近战攻击特效 - 闪烁的小红点 */
        .melee-effect {
            position: absolute;
            width: 6px;
            height: 6px;
            background-color: #dc2626;
            border-radius: 50%;
            animation: blink 0.5s infinite alternate;
        }
        
        @keyframes blink {
            from { opacity: 0.3; transform: scale(0.8); }
            to { opacity: 1; transform: scale(1.2); }
        }
        
        /* 炮兵攻击特效 - 炮弹和爆炸 */
        .cannon-effect {
            position: absolute;
            width: 8px;
            height: 8px;
            background-color: #f59e0b;
            border-radius: 50%;
            box-shadow: 0 0 5px rgba(245, 158, 11, 0.8);
            z-index: 60;
        }
        
        .explosion-effect {
            position: absolute;
            width: 20px;
            height: 20px;
            background-color: rgba(245, 158, 11, 0.7);
            border-radius: 50%;
            box-shadow: 0 0 10px rgba(245, 158, 11, 0.8);
            animation: explode 0.5s ease-out;
            z-index: 70;
        }
        
        @keyframes explode {
            0% { transform: scale(0); opacity: 1; }
            70% { transform: scale(1.2); opacity: 0.8; }
            100% { transform: scale(1.5); opacity: 0; }
        }
        
        /* 范围攻击指示器 */
        .area-indicator {
            position: absolute;
            border: 2px dashed #f59e0b;
            background-color: rgba(245, 158, 11, 0.1);
            z-index: 40;
        }
        
        /* 响应式调整 */
        @media (max-width: 768px) {
            .unit-icon {
                font-size: 12px;
            }
            
            .grid-cell {
                font-size: 10px;
            }
        }
    </style>
</head>
<body class="bg-gray-50 p-4 min-h-screen">
    <div class="max-w-6xl mx-auto">
        <!-- 游戏标题 -->
        <header class="text-center mb-6">
            <h1 class="text-2xl font-bold text-gray-800 mb-2">红蓝军队网格战棋</h1>
            <p class="text-gray-600">10×10正方形网格 | 血量系统 | 范围攻击特效</p>
        </header>
        
        <!-- 主要游戏区域 -->
        <div class="flex flex-col md:flex-row gap-6">
            <!-- 网格地图区域 -->
            <div class="md:w-1/2">
                <div class="bg-white p-4 rounded-lg shadow-lg relative">
                    <div class="flex justify-between items-center mb-3">
                        <h2 class="font-bold text-gray-700">游戏地图</h2>
                        <div class="text-sm text-gray-500">
                            坐标范围: 1-9
                        </div>
                    </div>
                    <div class="grid-container">
                        <div class="grid-wrapper">
                            <!-- 特效容器 - 用于绘制所有攻击特效 -->
                            <div class="effects-container" id="effectsContainer"></div>
                            <!-- 网格容器 -->
                            <div id="grid" class="grid-inner"></div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 控制面板区域 -->
            <div class="md:w-1/2 flex flex-col gap-4">
                <!-- 红方命令输入 -->
                <div class="bg-white p-4 rounded-lg shadow-lg border-t-4 border-red-500">
                    <h3 class="text-lg font-bold text-red-500 mb-3 flex items-center">
                        <i class="fa fa-chess-pawn mr-2"></i>红方命令
                    </h3>
                    <input type="text" id="redCommand" 
                           class="w-full p-2 border border-gray-300 rounded mb-2 focus:outline-none focus:ring-2 focus:ring-red-300"
                           placeholder="buy 步 3,4">
                    <button id="redExecute" class="w-full bg-red-500 text-white p-2 rounded hover:bg-red-600 transition-colors">
                        执行命令
                    </button>
                    <div class="text-xs text-gray-500 mt-2">
                        示例: "buy 炮 5,2" 表示在(5,2)位置购买炮兵
                    </div>
                </div>
                
                <!-- 蓝方命令输入 -->
                <div class="bg-white p-4 rounded-lg shadow-lg border-t-4 border-blue-500">
                    <h3 class="text-lg font-bold text-blue-500 mb-3 flex items-center">
                        <i class="fa fa-chess-pawn mr-2"></i>蓝方命令
                    </h3>
                    <input type="text" id="blueCommand" 
                           class="w-full p-2 border border-gray-300 rounded mb-2 focus:outline-none focus:ring-2 focus:ring-blue-300"
                           placeholder="buy 工 7,2">
                    <button id="blueExecute" class="w-full bg-blue-500 text-white p-2 rounded hover:bg-blue-600 transition-colors">
                        执行命令
                    </button>
                    <div class="text-xs text-gray-500 mt-2">
                        示例: "buy 医 3,8" 表示在(3,8)位置购买医疗兵
                    </div>
                </div>
                
                <!-- 兵种属性说明 -->
                <div class="bg-white p-4 rounded-lg shadow-lg">
                    <h3 class="text-lg font-bold text-gray-800 mb-3">兵种属性</h3>
                    <div class="space-y-2 text-sm">
                        <div class="flex justify-between">
                            <span><span class="font-semibold">步:</span> 步兵</span>
                            <span>血量: 200 | 攻击力: 100</span>
                        </div>
                        <div class="flex justify-between">
                            <span><span class="font-semibold">炮:</span> 炮兵</span>
                            <span>血量: 100 | 攻击力: 500 (范围攻击)</span>
                        </div>
                        <div class="flex justify-between">
                            <span><span class="font-semibold">医:</span> 医疗兵</span>
                            <span>血量: 150 | 无攻击能力</span>
                        </div>
                        <div class="flex justify-between">
                            <span><span class="font-semibold">工:</span> 工兵</span>
                            <span>血量: 150 | 攻击力: 50</span>
                        </div>
                        <div class="flex justify-between">
                            <span><span class="font-semibold">陆:</span> 陆兵</span>
                            <span>血量: 180 | 攻击力: 80</span>
                        </div>
                    </div>
                </div>
                
                <!-- 战斗日志 -->
                <div class="bg-white p-4 rounded-lg shadow-lg">
                    <h3 class="text-lg font-bold text-gray-800 mb-3">战斗日志</h3>
                    <div id="log" class="h-40 overflow-y-auto text-sm border border-gray-200 p-2 rounded">
                        <p class="text-gray-500">游戏准备就绪，请输入命令</p>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 页脚说明 -->
        <footer class="mt-8 text-center text-gray-500 text-sm">
            <p>炮兵会攻击正前方第5格并造成范围伤害（含相邻格子）| 范围伤害不分敌我 | 命令格式：buy [兵种] [x,y]</p>
        </footer>
    </div>

    <script>
        // 兵种属性配置
        const unitConfig = {
            '步': { health: 200, attack: 100 },    // 步兵
            '炮': { health: 100, attack: 500 },    // 炮兵
            '医': { health: 150, attack: 0 },      // 医疗兵
            '工': { health: 150, attack: 50 },     // 工兵
            '陆': { health: 180, attack: 80 }      // 陆兵
        };
        
        // 游戏状态数据
        const game = {
            size: 10,  // 10×10网格
            grid: Array(10).fill().map(() => Array(10).fill(null)),  // 初始化空网格
            effects: [], // 存储所有特效
            effectIntervals: [], // 存储特效定时器
            // 炮兵默认攻击方向: 上、右、下、左，循环切换
            cannonDirections: {} 
        };
        
        // 初始化网格
        function initGrid() {
            const grid = document.getElementById('grid');
            grid.innerHTML = '';
            
            // 创建带坐标标签的10×10网格
            for (let y = 0; y < game.size; y++) {
                for (let x = 0; x < game.size; x++) {
                    const cell = document.createElement('div');
                    cell.className = 'grid-cell';
                    cell.dataset.x = x;
                    cell.dataset.y = y;
                    
                    // 左上角单元格（坐标说明）
                    if (x === 0 && y === 0) {
                        cell.textContent = 'x\\y';
                        cell.classList.add('x-label', 'y-label');
                    }
                    // 第一行（x坐标标签）
                    else if (y === 0) {
                        cell.textContent = x;
                        cell.classList.add('x-label');
                    }
                    // 第一列（y坐标标签）
                    else if (x === 0) {
                        cell.textContent = y;
                        cell.classList.add('y-label');
                    }
                    
                    // 点击单元格显示坐标
                    cell.addEventListener('click', () => {
                        log(`点击坐标: (${x}, ${y})`);
                    });
                    
                    grid.appendChild(cell);
                }
            }
            
            // 开始战斗检测循环
            startBattleDetection();
        }
        
        // 在指定位置放置单位
        function placeUnit(x, y, type, army) {
            // 检查坐标是否有效（1-9范围，排除标签行和列）
            if (x < 1 || x >= game.size || y < 1 || y >= game.size) {
                log(`坐标(${x}, ${y})无效，范围应为1-9`);
                return false;
            }
            
            // 检查该位置是否已有单位
            if (game.grid[y][x]) {
                log(`坐标(${x}, ${y})已存在单位，无法重复放置`);
                return false;
            }
            
            // 获取单位配置
            const config = unitConfig[type];
            if (!config) {
                log(`未知兵种: ${type}`);
                return false;
            }
            
            // 计算单元格索引（考虑第一行和第一列是标签）
            const index = y * game.size + x;
            const cell = document.querySelectorAll('.grid-cell')[index];
            
            // 创建单位元素（包含血量条）
            const unit = document.createElement('div');
            unit.className = `unit-icon ${army === 'red' ? 'red-unit' : 'blue-unit'}`;
            
            // 创建血量条
            const healthBar = document.createElement('div');
            healthBar.className = 'health-bar';
            
            const healthValue = document.createElement('div');
            healthValue.className = 'health-value';
            healthValue.style.width = '100%';
            
            healthBar.appendChild(healthValue);
            
            // 创建兵种文字
            const unitType = document.createElement('div');
            unitType.textContent = type;
            
            unit.appendChild(healthBar);
            unit.appendChild(unitType);
            
            // 清空单元格并添加单位
            cell.innerHTML = '';
            cell.appendChild(unit);
            
            // 为炮兵初始化攻击方向
            let direction = null;
            if (type === '炮') {
                direction = 0; // 0:上, 1:右, 2:下, 3:左
                game.cannonDirections[`${x},${y}`] = direction;
            }
            
            // 更新游戏状态
            game.grid[y][x] = { 
                type, 
                army, 
                health: config.health,
                maxHealth: config.health,
                attack: config.attack,
                element: unit,
                healthElement: healthValue,
                direction: direction
            };
            
            // 放置单位后检查是否有战斗发生
            checkBattles();
            
            return true;
        }
        
        // 更新单位血量显示
        function updateHealthDisplay(unit) {
            if (!unit || !unit.healthElement) return;
            
            const percentage = (unit.health / unit.maxHealth) * 100;
            unit.healthElement.style.width = `${percentage}%`;
            
            // 更新血量条颜色
            unit.healthElement.classList.remove('health-low', 'health-critical');
            if (percentage < 30) {
                unit.healthElement.classList.add('health-critical');
            } else if (percentage < 60) {
                unit.healthElement.classList.add('health-low');
            }
        }
        
        // 对单位造成伤害
        function damageUnit(x, y, damage) {
            const unit = game.grid[y][x];
            if (!unit) return false;
            
            unit.health -= damage;
            updateHealthDisplay(unit);
            
            // 记录伤害日志
            const armyName = unit.army === 'red' ? '红方' : '蓝方';
            log(`${armyName}${getUnitName(unit.type)} 受到 ${damage} 点伤害，剩余血量: ${Math.max(0, unit.health)}`);
            
            // 检查单位是否已死亡
            if (unit.health <= 0) {
                log(`${armyName}${getUnitName(unit.type)} 已被消灭!`);
                
                // 清除单位
                const index = y * game.size + x;
                const cell = document.querySelectorAll('.grid-cell')[index];
                cell.innerHTML = '';
                
                // 如果是炮兵，清除其方向记录
                if (unit.type === '炮') {
                    delete game.cannonDirections[`${x},${y}`];
                }
                
                game.grid[y][x] = null;
                return true;
            }
            
            return false;
        }
        
        // 计算两个单位之间的距离
        function calculateDistance(x1, y1, x2, y2) {
            // 使用曼哈顿距离计算
            return Math.max(Math.abs(x1 - x2), Math.abs(y1 - y2));
        }
        
        // 检查是否有战斗发生
        function checkBattles() {
            // 清除现有特效
            clearAllEffects();
            
            // 收集所有单位
            const units = [];
            for (let y = 1; y < game.size; y++) {
                for (let x = 1; x < game.size; x++) {
                    if (game.grid[y][x]) {
                        units.push({ ...game.grid[y][x], x, y });
                    }
                }
            }
            
            // 处理近战单位（步、医、工、陆）的战斗
            const meleeUnits = units.filter(unit => ['步', '医', '工', '陆'].includes(unit.type));
            for (let i = 0; i < meleeUnits.length; i++) {
                for (let j = i + 1; j < meleeUnits.length; j++) {
                    const unitA = meleeUnits[i];
                    const unitB = meleeUnits[j];
                    
                    // 不同阵营且距离为1或0（相邻或同格）
                    if (unitA.army !== unitB.army) {
                        const distance = calculateDistance(unitA.x, unitA.y, unitB.x, unitB.y);
                        if (distance <= 1) {
                            // 互相攻击
                            damageUnit(unitB.x, unitB.y, unitA.attack);
                            damageUnit(unitA.x, unitA.y, unitB.attack);
                            
                            // 创建近战特效
                            createMeleeEffect(unitA.x, unitA.y, unitB.x, unitB.y);
                        }
                    }
                }
            }
            
            // 处理炮兵攻击（攻击正前方第5格，范围伤害）
            const cannonUnits = units.filter(unit => unit.type === '炮');
            cannonUnits.forEach(cannon => {
                // 确定攻击方向（上、右、下、左循环）
                const directions = [
                    { dx: 0, dy: -1 },  // 上
                    { dx: 1, dy: 0 },   // 右
                    { dx: 0, dy: 1 },   // 下
                    { dx: -1, dy: 0 }   // 左
                ];
                
                // 更新方向（每次攻击后切换方向）
                const key = `${cannon.x},${cannon.y}`;
                cannon.direction = (cannon.direction + 1) % 4;
                game.cannonDirections[key] = cannon.direction;
                const dir = directions[cannon.direction];
                
                // 计算目标位置（正前方第5格）
                const targetX = cannon.x + dir.dx * 5;
                const targetY = cannon.y + dir.dy * 5;
                
                // 检查目标位置是否在网格范围内
                if (targetX >= 1 && targetX <= 9 && targetY >= 1 && targetY <= 9) {
                    log(`${cannon.army === 'red' ? '红方' : '蓝方'}炮兵从(${cannon.x},${cannon.y})向` + 
                        `${getDirectionName(cannon.direction)}方向(${targetX},${targetY})发射炮弹!`);
                    
                    // 创建炮弹飞行特效
                    createCannonEffect(cannon.x, cannon.y, targetX, targetY, () => {
                        // 炮弹命中后产生范围伤害
                        createExplosionEffect(targetX, targetY);
                        applyAreaDamage(targetX, targetY, cannon.attack);
                    });
                } else {
                    log(`${cannon.army === 'red' ? '红方' : '蓝方'}炮兵从(${cannon.x},${cannon.y})向` + 
                        `${getDirectionName(cannon.direction)}方向发射，但目标超出范围!`);
                }
            });
        }
        
        // 获取方向名称
        function getDirectionName(direction) {
            const dirNames = ['上', '右', '下', '左'];
            return dirNames[direction] || '未知';
        }
        
        // 应用范围伤害（目标格及上下左右相邻格）
        function applyAreaDamage(centerX, centerY, damage) {
            // 定义范围：中心格和四个方向的相邻格
            const area = [
                {x: centerX, y: centerY},          // 中心格
                {x: centerX, y: centerY - 1},      // 上
                {x: centerX, y: centerY + 1},      // 下
                {x: centerX - 1, y: centerY},      // 左
                {x: centerX + 1, y: centerY}       // 右
            ];
            
            // 显示范围指示器
            showAreaIndicator(centerX, centerY);
            
            // 对范围内的所有单位造成伤害（不分敌我）
            area.forEach(pos => {
                if (pos.x >= 1 && pos.x <= 9 && pos.y >= 1 && pos.y <= 9) {
                    if (game.grid[pos.y][pos.x]) {
                        damageUnit(pos.x, pos.y, damage);
                    }
                }
            });
        }
        
        // 显示范围攻击指示器
        function showAreaIndicator(centerX, centerY) {
            const effectsContainer = document.getElementById('effectsContainer');
            const cellSize = 100 / (game.size - 1); // 计算每个单元格的百分比宽度
            
            // 计算范围指示器位置和大小
            const startX = (centerX - 2) * cellSize;
            const startY = (centerY - 2) * cellSize;
            const size = cellSize * 3;
            
            const indicator = document.createElement('div');
            indicator.className = 'area-indicator';
            indicator.style.left = `${startX}%`;
            indicator.style.top = `${startY}%`;
            indicator.style.width = `${size}%`;
            indicator.style.height = `${size}%`;
            
            effectsContainer.appendChild(indicator);
            game.effects.push(indicator);
            
            // 3秒后移除指示器
            setTimeout(() => {
                if (indicator.parentNode) {
                    indicator.parentNode.removeChild(indicator);
                    game.effects = game.effects.filter(e => e !== indicator);
                }
            }, 3000);
        }
        
        // 创建近战攻击特效（闪烁小红点）
        function createMeleeEffect(x1, y1, x2, y2) {
            const effectsContainer = document.getElementById('effectsContainer');
            const cellSize = 100 / (game.size - 1); // 计算每个单元格的百分比宽度
            
            // 计算两个单位之间的所有点
            const points = getLinePoints(x1, y1, x2, y2);
            
            // 在每个点上创建闪烁的小红点
            points.forEach(({x, y}, index) => {
                // 计算在容器中的百分比位置
                const posX = (x - 1) * cellSize;
                const posY = (y - 1) * cellSize;
                
                const effect = document.createElement('div');
                effect.className = 'melee-effect';
                effect.style.left = `${posX + cellSize/2}%`;
                effect.style.top = `${posY + cellSize/2}%`;
                effect.style.animationDelay = `${index * 0.1}s`; // 错开动画时间
                
                effectsContainer.appendChild(effect);
                game.effects.push(effect);
                
                // 5秒后移除特效
                setTimeout(() => {
                    if (effect.parentNode) {
                        effect.parentNode.removeChild(effect);
                        game.effects = game.effects.filter(e => e !== effect);
                    }
                }, 5000);
            });
        }
        
        // 创建炮兵攻击特效（炮弹飞行）
        function createCannonEffect(x1, y1, x2, y2, onImpact) {
            const effectsContainer = document.getElementById('effectsContainer');
            const cellSize = 100 / (game.size - 1); // 计算每个单元格的百分比宽度
            
            // 创建炮弹元素
            const cannonball = document.createElement('div');
            cannonball.className = 'cannon-effect';
            effectsContainer.appendChild(cannonball);
            game.effects.push(cannonball);
            
            // 计算起始和结束位置（百分比）
            const startX = (x1 - 1) * cellSize + cellSize/2;
            const startY = (y1 - 1) * cellSize + cellSize/2;
            const endX = (x2 - 1) * cellSize + cellSize/2;
            const endY = (y2 - 1) * cellSize + cellSize/2;
            
            // 设置初始位置
            cannonball.style.left = `${startX}%`;
            cannonball.style.top = `${startY}%`;
            
            // 动画参数
            const duration = 1500; // 动画持续时间（毫秒）
            const startTime = Date.now();
            
            // 创建炮弹飞行动画
            const animateCannonball = () => {
                const currentTime = Date.now();
                const elapsed = currentTime - startTime;
                const progress = Math.min(elapsed / duration, 1);
                
                // 计算当前位置（贝塞尔曲线使轨迹更自然）
                const x = startX + (endX - startX) * progress;
                const y = startY + (endY - startY) * progress + 
                          Math.sin(progress * Math.PI) * 10; // 抛物线效果
                
                cannonball.style.left = `${x}%`;
                cannonball.style.top = `${y}%`;
                
                if (progress < 1) {
                    requestAnimationFrame(animateCannonball);
                } else {
                    // 动画结束，移除炮弹
                    if (cannonball.parentNode) {
                        cannonball.parentNode.removeChild(cannonball);
                        game.effects = game.effects.filter(e => e !== cannonball);
                    }
                    
                    // 触发命中回调
                    if (onImpact) onImpact();
                }
            };
            
            // 开始动画
            requestAnimationFrame(animateCannonball);
        }
        
        // 创建爆炸特效
        function createExplosionEffect(x, y) {
            const effectsContainer = document.getElementById('effectsContainer');
            const cellSize = 100 / (game.size - 1); // 计算每个单元格的百分比宽度
            
            // 计算位置（百分比）
            const posX = (x - 1) * cellSize + cellSize/2;
            const posY = (y - 1) * cellSize + cellSize/2;
            
            const explosion = document.createElement('div');
            explosion.className = 'explosion-effect';
            explosion.style.left = `${posX}%`;
            explosion.style.top = `${posY}%`;
            explosion.style.transform = 'translate(-50%, -50%)';
            
            effectsContainer.appendChild(explosion);
            game.effects.push(explosion);
            
            // 动画结束后移除爆炸效果
            setTimeout(() => {
                if (explosion.parentNode) {
                    explosion.parentNode.removeChild(explosion);
                    game.effects = game.effects.filter(e => e !== explosion);
                }
            }, 500);
        }
        
        // 获取两点之间的所有点（用于近战特效）
        function getLinePoints(x1, y1, x2, y2) {
            const points = [];
            const dx = Math.abs(x2 - x1);
            const dy = Math.abs(y2 - y1);
            const sx = x1 < x2 ? 1 : -1;
            const sy = y1 < y2 ? 1 : -1;
            let x = x1;
            let y = y1;
            let err = dx - dy;
            
            while (true) {
                points.push({x, y});
                if (x === x2 && y === y2) break;
                const e2 = 2 * err;
                if (e2 > -dy) {
                    err -= dy;
                    x += sx;
                }
                if (e2 < dx) {
                    err += dx;
                    y += sy;
                }
            }
            
            return points;
        }
        
        // 清除所有特效
        function clearAllEffects() {
            // 清除所有特效元素
            game.effects.forEach(effect => {
                if (effect.parentNode) {
                    effect.parentNode.removeChild(effect);
                }
            });
            game.effects = [];
            
            // 清除所有定时器
            game.effectIntervals.forEach(interval => clearInterval(interval));
            game.effectIntervals = [];
        }
        
        // 开始战斗检测循环
        function startBattleDetection() {
            // 每5秒检查一次战斗状态
            setInterval(checkBattles, 5000);
        }
        
        // 解析并执行命令
        function parseCommand(command, army) {
            const parts = command.trim().split(/\s+/);
            
            // 验证命令格式
            if (parts.length !== 3 || parts[0].toLowerCase() !== 'buy') {
                log('命令格式错误，正确格式: buy 兵种 坐标(如: buy 步 3,4)');
                return;
            }
            
            const type = parts[1];
            const coords = parts[2].split(',');
            
            // 验证坐标格式
            if (coords.length !== 2) {
                log('坐标格式错误，正确格式: x,y(如: 3,4)');
                return;
            }
            
            const x = parseInt(coords[0]);
            const y = parseInt(coords[1]);
            
            // 验证坐标是否为数字
            if (isNaN(x) || isNaN(y)) {
                log('坐标必须是数字，请使用如 "3,4" 的格式');
                return;
            }
            
            // 验证兵种是否有效
            const validTypes = ['步', '炮', '医', '工', '陆'];
            if (!validTypes.includes(type)) {
                log(`无效兵种: ${type}，可用兵种: 步, 炮, 医, 工, 陆`);
                return;
            }
            
            // 放置单位并记录日志
            if (placeUnit(x, y, type, army)) {
                const armyName = army === 'red' ? '红方' : '蓝方';
                const typeNames = { 
                    '步': '步兵', 
                    '炮': '炮兵', 
                    '医': '医疗兵', 
                    '工': '工兵', 
                    '陆': '陆兵' 
                };
                log(`${armyName}在(${x}, ${y})放置了${typeNames[type]}`);
            }
        }
        
        // 获取兵种名称
        function getUnitName(abbreviation) {
            const names = {
                '步': '步兵',
                '炮': '炮兵',
                '医': '医疗兵',
                '工': '工兵',
                '陆': '陆兵'
            };
            return names[abbreviation] || abbreviation;
        }
        
        // 日志记录功能
        function log(message) {
            const logElement = document.getElementById('log');
            const timestamp = new Date().toLocaleTimeString();
            const entry = document.createElement('p');
            entry.innerHTML = `[${timestamp}] ${message}`;
            
            // 添加到日志顶部
            logElement.insertBefore(entry, logElement.firstChild);
            
            // 保持滚动在顶部
            logElement.scrollTop = 0;
        }
        
        // 初始化事件监听
        function initEvents() {
            // 红方命令执行
            document.getElementById('redExecute').addEventListener('click', () => {
                const command = document.getElementById('redCommand').value;
                parseCommand(command, 'red');
                document.getElementById('redCommand').value = '';
                document.getElementById('redCommand').focus();
            });
            
            // 蓝方命令执行
            document.getElementById('blueExecute').addEventListener('click', () => {
                const command = document.getElementById('blueCommand').value;
                parseCommand(command, 'blue');
                document.getElementById('blueCommand').value = '';
                document.getElementById('blueCommand').focus();
            });
            
            // 支持回车键执行命令
            document.getElementById('redCommand').addEventListener('keypress', (e) => {
                if (e.key === 'Enter') document.getElementById('redExecute').click();
            });
            
            document.getElementById('blueCommand').addEventListener('keypress', (e) => {
                if (e.key === 'Enter') document.getElementById('blueExecute').click();
            });
        }
        
        // 初始化游戏
        function init() {
            initGrid();
            initEvents();
        }
        
        // 页面加载完成后初始化游戏
        window.addEventListener('DOMContentLoaded', init);
    </script>
</body>
</html>
    